package com.athuahua.spzx.service.impl;

import cn.hutool.core.date.DateTime;
import com.alibaba.fastjson2.JSON;
import com.athuahua.spzx.dto.product.SkuSaleDto;
import com.athuahua.spzx.entity.OrderInfo;
import com.athuahua.spzx.entity.OrderItem;
import com.athuahua.spzx.feignapi.OrderFeignClient;
import com.athuahua.spzx.feignapi.ProductFeignClient;
import com.athuahua.spzx.properties.JwtProperties;
import com.athuahua.spzx.utils.JwtUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.athuahua.spzx.entity.PaymentInfo;
import com.athuahua.spzx.service.PaymentInfoService;
import com.athuahua.spzx.mapper.PaymentInfoMapper;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author huahua
 * @description 针对表【payment_info(付款信息表)】的数据库操作Service实现
 * @createDate 2024-08-23 16:16:55
 */
@Service
public class PaymentInfoServiceImpl extends ServiceImpl<PaymentInfoMapper, PaymentInfo>
        implements PaymentInfoService {

    @Resource
    private PaymentInfoMapper paymentInfoMapper;

    @Resource
    private OrderFeignClient orderFeignClient;

    @Resource
    private ProductFeignClient productFeignClient;

    @Resource
    private JwtProperties jwtProperties;

    @Override
    public PaymentInfo savePaymentInfo(String orderNo) {
        //1.根据orderNo查询支付记录表，支付记录是否存在
        PaymentInfo paymentInfo = paymentInfoMapper.selectOne(new LambdaQueryWrapper<PaymentInfo>()
                .eq(PaymentInfo::getOrderNo, orderNo));
        if (paymentInfo == null) {
            //1.1 如果不存在，则查询订单信息 openfeign远程 service-order -> 根据订单编号返回订单信息
            OrderInfo orderInfo = orderFeignClient.getOrderInfoByOrderNo(orderNo);
            paymentInfo = new PaymentInfo();
            paymentInfo.setUserId(orderInfo.getUserId());
            paymentInfo.setPayType(orderInfo.getPayType());
            StringBuilder content = new StringBuilder();
            for(OrderItem item : orderInfo.getOrderItemList()){
                content.append(item.getSkuName()).append(" ");
            }
            paymentInfo.setContent(content.toString());
            paymentInfo.setAmount(orderInfo.getTotalAmount());
            paymentInfo.setOrderNo(orderInfo.getOrderNo());
            paymentInfo.setPaymentStatus(String.valueOf(0));
            paymentInfoMapper.insert(paymentInfo);

        }


        //1.2 存在直接返回
        return paymentInfo;
    }

    /**
     * 支付宝返回的map数据
     * "trade_status" 交易状态
     * "out_trade_no" 订单编号
     */
    @Override
    public void updatePaymentStatus(Map<String, String> alipayMap) {
        //获得订单编号
        String orderNo = alipayMap.get("out_trade_no");
        PaymentInfo paymentInfo = paymentInfoMapper.selectOne(new LambdaQueryWrapper<PaymentInfo>()
                .eq(PaymentInfo::getOrderNo, orderNo));

        //判断是否已完成
        if(Integer.parseInt(paymentInfo.getPaymentStatus()) == 1){
            return;
        }

        //更新支付状态
        paymentInfo.setPaymentStatus(String.valueOf(1));
        paymentInfo.setOutTradeNo(alipayMap.get("trade_no"));
        paymentInfo.setCallbackTime(DateTime.now());
        paymentInfo.setCallbackContent(JSON.toJSONString(alipayMap));
        paymentInfoMapper.updateById(paymentInfo);



        //更新订单状态
        orderFeignClient.updateOrderStatus(paymentInfo.getOrderNo(),1);



        //更新SKU商品销量
        OrderInfo orderInfo = orderFeignClient.getOrderInfoByOrderNo(paymentInfo.getOrderNo());
        List<SkuSaleDto> skuSaleDtoList = orderInfo.getOrderItemList().stream().map(item -> {
            SkuSaleDto skuSaleDto = new SkuSaleDto();
            skuSaleDto.setSkuId(item.getSkuId());
            skuSaleDto.setNum(item.getSkuNum());
            return skuSaleDto;
        }).collect(Collectors.toList());
        productFeignClient.updateSkuSaleNum(skuSaleDtoList);
    }

    @Override
    public void testUpdatePaymentStatus() {
//        String orderNo = "1-1724658502954";
//        PaymentInfo paymentInfo = paymentInfoMapper.selectOne(new LambdaQueryWrapper<PaymentInfo>()
//                .eq(PaymentInfo::getOrderNo, orderNo));
//
//        //更新订单状态
//        orderFeignClient.updateOrderStatus(paymentInfo.getOrderNo(),1);
//
//
//        OrderInfo orderInfo = orderFeignClient.getOrderInfoByOrderNo(paymentInfo.getOrderNo());
//        List<SkuSaleDto> skuSaleDtoList = orderInfo.getOrderItemList().stream().map(item -> {
//            SkuSaleDto skuSaleDto = new SkuSaleDto();
//            skuSaleDto.setSkuId(item.getSkuId());
//            skuSaleDto.setNum(item.getSkuNum());
//            return skuSaleDto;
//        }).collect(Collectors.toList());
//
//        productFeignClient.updateSkuSaleNum(skuSaleDtoList);

    }

}




